package com.party.jackclientandroid.controller;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;

import com.party.jackclientandroid.StartActivity;
import com.party.jackclientandroid.okhttp.RetrofitRxClient;
import com.party.jackclientandroid.api.AppUpdateRxAPI;
import com.party.jackclientandroid.api.DefaultConsumer;
import com.party.jackclientandroid.BaseActivity;
import com.party.jackclientandroid.MApplication;
import com.party.jackclientandroid.bean.AppUpdateBean;
import com.party.jackclientandroid.bean.BaseResult;
import com.party.jackclientandroid.okhttp.OkHttpUtils;
import com.party.jackclientandroid.okhttp.callback.FileCallBack;
import com.party.jackclientandroid.utils.ConstUtils;
import com.party.jackclientandroid.utils.FileProvider7;
import com.party.jackclientandroid.utils.MPackageUtils;
import com.party.jackclientandroid.utils.NetworkUtils;
import com.party.jackclientandroid.utils.ToastUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import okhttp3.Call;

/**
 * Created by tangxuebing on 2018/5/14.
 */

public class AppUpdateController {
    private BaseActivity mActivity;
    private AppUpdateListener updateListener;
    private AlertDialog mAlertDialog;
    private ProgressDialog mApkDownloadDialog;
    private AppUpdateBean mUpdateBean;
    private File mDownloadApkFile;

    public interface AppUpdateListener {
        /**
         * 应用没有更新
         */
        void notUpdate(boolean showMsg);
    }

    public AppUpdateController(BaseActivity activity, AppUpdateListener listener) {
        this.mActivity = activity;
        this.updateListener = listener;
    }

    /**
     * 获取app升级信息
     *
     * @return
     */
    public Observable<BaseResult<AppUpdateBean>> getAppUpdate() {
        String packageName = mActivity.getPackageName();
        int versionCode = MPackageUtils.getVersionCode(mActivity);
        String versionName = MPackageUtils.getVersionName(mActivity);
        Map<String, String> data = new HashMap<>();
        data.put("versionCode", versionCode + "");
        data.put("type", ConstUtils.CURRENT_APP_TYPE + "");
        data.put("versionName", versionName);
        data.put("packageName", packageName);
        return RetrofitRxClient.INSTANCE
                .getRetrofit()
                .create(AppUpdateRxAPI.class)
                .getAppUpdate(data);
    }

    /**
     * 检查更新
     */
    public void checkAppUpdate() {
        mActivity.addDisposableIoMain(getAppUpdate(), new DefaultConsumer<AppUpdateBean>((MApplication) mActivity.getApplication()) {
            @Override
            public void operateError(String message) {
                super.operateError(message);
                updateListener.notUpdate(true);
            }

            @Override
            public void operateSuccess(BaseResult<AppUpdateBean> baseBean) {
                if (baseBean.getData() == null || TextUtils.isEmpty(baseBean.getData().getApkDownLoadUrl())) {
                    updateListener.notUpdate(true);
                    return;
                }
                if (baseBean.getData().getVersionCode() > MPackageUtils.getVersionCode(mActivity)) {
                    mUpdateBean = baseBean.getData();
                    showAppUpdateTipDialog();
                } else {
                    updateListener.notUpdate(true);
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                updateListener.notUpdate(true);
            }
        });
    }

    /**
     * 显示更新提示框
     */
    private void showAppUpdateTipDialog() {
        String title = "更新提示:wifi环境";
        String btnName = "开始升级";
        if (!NetworkUtils.wifiIsConnect()) {
            title = "更新提示：非wifi状态";
            btnName = "流量升级";
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setTitle(title);
        builder.setCancelable(false);
        if (TextUtils.isEmpty(mUpdateBean.getCurrentVersionDesc()) || mUpdateBean.getCurrentVersionDesc().equals("null")) {
            builder.setMessage("强制升级应用咯。。。。");
        } else {
            builder.setMessage(mUpdateBean.getCurrentVersionDesc());
        }
        builder.setPositiveButton(btnName, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                showApkDownloadDialog();
            }
        });

        String exitText = "下次";
        if (mUpdateBean.isForceUpdate()) {
            exitText = "退出";
        }
        builder.setNeutralButton(exitText, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (mUpdateBean.isForceUpdate()) {
                    mActivity.finish();
                } else {
                    mAlertDialog.dismiss();
                    updateListener.notUpdate(false);
                }
            }
        });
        mAlertDialog = builder.show();
    }

    /**
     * 显示下载进度框
     */
    public void showApkDownloadDialog() {
        if (mActivity instanceof StartActivity) {
            boolean hasPer = ((StartActivity) mActivity).isHasPer();
            if (!hasPer) {
                ((StartActivity) mActivity).applyNeedPermissions();
                return;
            }
        }
//        else if (mActivity instanceof LoginActivity) {
//            boolean hasPer = ((LoginActivity) mActivity).isHasPer();
//            if (!hasPer) {
//                ((LoginActivity) mActivity).applyNeedPermissions();
//                return;
//            }
//        }
        mApkDownloadDialog = createProgressDialog();
        mApkDownloadDialog.show();
        // 先创建下载目录
        File file = new File(Environment.getExternalStorageDirectory(), "KillDebug_Download_App");
        if (!file.exists()) {
            file.mkdir();
        }
        String downloadDir = file.getAbsolutePath();
        String versionName = TextUtils.isEmpty(mUpdateBean.getVersionName()) ? "" : mUpdateBean.getVersionName();
        String fileName = "killdebug_operater" + versionName + "_.apk";
        // 如果存在apk文件,先删除
        File apkFile = new File(file, fileName);
        if (apkFile.exists()) {
            apkFile.delete();
        }
        OkHttpUtils.get()
                .tag(mUpdateBean.getApkDownLoadUrl())
                .url(mUpdateBean.getApkDownLoadUrl())
                .build()
                .execute(new FileCallBack(downloadDir, fileName) {
                    @Override
                    public void inProgress(float progress, long total, int id) {
                        mApkDownloadDialog.setProgress((int) (progress * 100));
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        mApkDownloadDialog.dismiss();
                        ToastUtils.t(mActivity.getApplication(), "下载失败," + e.getMessage());
                    }

                    @Override
                    public void onResponse(File response, int id) {
                        mApkDownloadDialog.dismiss();
                        mDownloadApkFile = response;
                        doInstallWork(response);
                    }
                });
    }

    /**
     * 解决Android 8.0安装apk失败的问题
     *
     * @param response
     */
    private void doInstallWork(File response) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            boolean hasInstallPermission = isHasInstallPermissionWithO(mActivity);
            if (hasInstallPermission) {
                installApk(response);
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                builder.setTitle("安装应用需要打开未知来源权限，请去设置中开启权限");
                builder.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                            startInstallPermissionSettingActivity();
                        }
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
        } else {
            installApk(response);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private boolean isHasInstallPermissionWithO(Context context) {
        if (context == null) {
            return false;
        }
        return context.getPackageManager().canRequestPackageInstalls();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity() {
        Uri packageURI = Uri.parse("package:" + mActivity.getPackageName());
        //注意这个是8.0新API
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        mActivity.startActivityForResult(intent, ConstUtils.MANAGE_UNKNOWN_APP_SOURCES_CODE);
    }

    /**
     * 用户授予安装未知源权限之后,继续安装文件
     */
    public void continueInstallApk() {
        installApk(mDownloadApkFile);
    }

    /**
     * 调用系统安装apk
     *
     * @param apkFile
     */
    public void installApk(File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        FileProvider7.setIntentDataAndType(mActivity, intent, "application/vnd.android.package-archive", apkFile, true);
        mActivity.startActivity(intent);
    }

    private ProgressDialog createProgressDialog() {
        ProgressDialog progressDialog = new ProgressDialog(mActivity);
        PackageManager pm = mActivity.getPackageManager();
        Drawable icon = mActivity.getApplicationInfo().loadIcon(pm);
        CharSequence label = mActivity.getApplicationInfo().loadLabel(pm);
        progressDialog.setTitle("正在更新" + label);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setIcon(icon);
        progressDialog.setMax(100);
        progressDialog.setCancelable(false);
        progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mApkDownloadDialog.dismiss();
                OkHttpUtils.getInstance().cancelTag(mUpdateBean.getApkDownLoadUrl());
            }
        });
        return progressDialog;
    }
}
